/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package EJB_GameLogic;

import EntityBeans.User;
import java.util.Iterator;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author DROWNE
 */
@Stateless
public class GameLogic implements GameLogicRemote {
    
    // Add business logic below. (Right-click in editor and choose
    // "Insert Code > Add Business Method")
    @PersistenceContext(unitName="HasServerPU")
    EntityManager em;

    @Override
    public int registerUser(String _username, String _password, String _nickName, String _email) {
        String query="select u from User u where u.username=:user";
        Query q=em.createQuery(query);
        q.setParameter("user", _username);
        Iterator itResult=q.getResultList().iterator();
        if(itResult.hasNext()){
            return -1;
        } else {
            User us = new User();
            us.setEmail(_email);
            us.setNickname(_nickName);
            us.setPassword(_password);
            us.setUsername(_username);
            em.persist(us);
            em.flush();
            return 1;
        }
    }

    @Override
    public int loginUser(String _username, String _password) {
        String query="select u from User u where u.username=:user and u.password=:pass";
        Query q=em.createQuery(query);
        q.setParameter("user", _username);

        q.setParameter("pass",_password);
        Iterator itResult=q.getResultList().iterator();

        if(itResult.hasNext()){
            return 1;
        }

        return 0;
    }


}
